<template>
    <view>
        <u-popup
            :closeOnClickOverlay="false"
            mode="center"
            round="30rpx"
            :safeAreaInsetBottom="false"
            :show="userInfoShow"
        >
            <view class="user-info">
                <view class="title">请填写您的信息</view>
                <view class="avatar">
                    <button
                        @chooseavatar="chooseavatar"
                        @tap="chooseavatar"
                        class="avatar-btn"
                        openType="chooseAvatar"
                        :plain="true"
                    >
                        <u-avatar size="129rpx" :src="avatar"></u-avatar>
                        <view class="tips">点击设置头像</view>
                    </button>
                </view>
                <view class="nickname">
                    <input
                        @focus="nicknameBlur"
                        border="none"
                        class="nickname-input"
                        placeholder="请输入昵称"
                        placeholderStyle="font-size: 28rpx"
                        type="nickname"
                        v-model="nickname"
                    />
                </view>
                <view @tap="userInfoConfirm" class="confirm">确定</view>
            </view>
        </u-popup>
    </view>
</template>

<script>
export default {
  data() {
    return {
      avatar: '',
      nickname: '',
      userInfoShow: false
    };
  },
  methods: {
    nicknameBlur(e) {
      this.nickname = e.detail.value;
    },
    chooseavatar(e) {
      var that = this;
      if (e.detail.avatarUrl) {
        that.uploadAvatar(e.detail.avatarUrl);
      } else {
        uni.chooseImage({
          count: 1,
          success: function (res) {
            that.uploadAvatar(res.tempFiles[0].path)
          }
        });
      }
    },
    uploadAvatar(tempFilePath) {
      this.$util.upload({
        url: '/upload/image',
        filePath: tempFilePath,
        name: 'image'
      }).then(res => {
        this.avatar = res.url
      })
    },
    userInfoConfirm() {
      if (!this.avatar) {
        this.$util.message('请设置头像')
        return
      }
      if (!this.nickname) {
        this.$util.message('请设置昵称')
        return
      }

      this.$util.request({
        url: '/user/setUserInfo',
        data: {
          avatar: this.avatar,
          nickname: this.nickname
        },
        loadingText: '正在保存'
      }).then(res => {
        uni.switchTab({
          url: '/pages/my/my'
        })
      })
    }
  }
}
</script>
<style>
@import './setUserAvatar.css';
</style>
